package cn.wolfcode.p2p.base.service.impl;

import cn.wolfcode.p2p.base.exception.CustomerException;
import cn.wolfcode.p2p.base.service.IVerifyCodeService;
import cn.wolfcode.p2p.base.util.Constant;
import cn.wolfcode.p2p.base.util.DateUtil;
import cn.wolfcode.p2p.base.util.UserContext;
import cn.wolfcode.p2p.base.vo.VerifyCodeVO;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {
    @Override
    public void sendVerifyCode(String phoneNumber) {
        // 1.如果之前给该手机号发送了短信,且在90s内,则不用发,抛出异常
        VerifyCodeVO vo = UserContext.getVerifyCodeVO();
//        if (vo != null && (((new Date()).getTime() - vo.getSendTime().getTime()) / 1000 < 90)) {
        if (vo != null &&
                DateUtil.getBetweenTime(new Date(), vo.getSendTime()) < Constant.VERIFY_CODE_INTERVAL_SECOND) {
            if (phoneNumber.equals(vo.getPhoneNumber())) {
                throw new CustomerException("短信发送太频繁,稍后再试");
            }
        }
        // 2.生成4位数的验证码(UUID,截取4位)
        String code = UUID.randomUUID().toString().substring(0, 4);
        // 3.发送手机短信,打印在控制台模拟
        System.out.println("验证码:" + code);
        //-------------------------------------
        // 真正的发送短信验证码

        //-----------------------------------------
        // 4.把验证码的信息(接受手机号码,验证码,发送时间存到session中,方便验证)
        vo = new VerifyCodeVO(phoneNumber, code, new Date());
        UserContext.setVerifyCodeVO(vo);
    }

    @Override
    public void validate(String username, String verifyCode) {
        // 已经发送了短信
        VerifyCodeVO vo = UserContext.getVerifyCodeVO();
        if (vo == null) {
            // 0.未发送的情况
            throw new CustomerException("请获取验证码");
        }
        // 1.接收短信的手机号和注册的手机一致
        if (!vo.getPhoneNumber().equals(username)) {
            throw new CustomerException("注册号码与验证手机不一致");

        }
        // 2.接收验证与注册的验证码一致
        if (!vo.getCode().equals(verifyCode)) {
            throw new CustomerException("验证码错误");
        }
        // 3.验证码有效时间是否在规定时间内(例如5分钟)
        if (DateUtil.getBetweenTime(new Date(), vo.getSendTime()) > Constant.VERIFY_CODE_VAILDATE_SECOND) {
            throw new CustomerException("验证码已过期,请重新获取");
        }
        // 验证成功后,将验证码从session中清空
        UserContext.setVerifyCodeVO(null);
    }
}
